<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="区域名称" prop="regionName">
        <el-input
          v-model="queryParams.regionName"
          placeholder="请输入区域名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="省份" prop="province">
        <el-input
          v-model="queryParams.province"
          placeholder="请输入省份"
          clearable
          @keyup.enter="handleQuery"
          style="width: 100px;"
        />
      </el-form-item>
      <el-form-item label="运营城市" prop="city">
        <el-input
          v-model="queryParams.city"
          placeholder="请输入运营城市"
          clearable
          @keyup.enter="handleQuery"
          style="width: 120px;"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" style="width: 120px;" clearable>
          <el-option
            v-for="dict in sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['business:operatingarea:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:operatingarea:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:operatingarea:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['business:operatingarea:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="operatingareaList" border @selection-change="handleSelectionChange">
      <el-table-column type="index" :index="indexMethod" />
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="id" align="center" prop="id" /> -->
      <el-table-column label="区域名称" align="center" prop="regionName" />
      <el-table-column label="省份" align="center" prop="province" />
      <el-table-column label="运营城市" align="center" prop="city" />
      <el-table-column label="区域" align="center" prop="region" />
      <el-table-column label="详细地址" align="center" prop="address" />
      <el-table-column label="配送员数量" align="center" prop="deleverNum" />
      <el-table-column label="状态" align="center">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            :disabled="loading"
            :active-value="0"
            :inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['business:operatingarea:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['business:operatingarea:remove']">删除</el-button>
        </template>
      </el-table-column> -->
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改运营区域对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body center>
      <el-row>
        <el-col :span="11">
          <el-form ref="operatingareaRef" :model="form" :rules="rules" label-width="80px" width="200px">
            <el-form-item label="区域名称" prop="regionName">
              <el-input v-model="form.regionName" placeholder="请输入区域名称" />
            </el-form-item>
            <el-form-item label="省份" prop="province">
              <el-input v-model="form.province" placeholder="请输入省份" />
            </el-form-item>
            <el-form-item label="运营城市" prop="city">
              <el-input v-model="form.city" placeholder="请输入运营城市" />
            </el-form-item>
            <el-form-item label="区域" prop="region">
              <!-- <el-input v-model="form.region" placeholder="请输入区域" /> -->
               <el-cascader ref="cascaderRef" v-model="form.regionCode" :options="regionOptions" :props="regionProps" separator="-" @change="handleChange" clearable style="width: 100%;" />
            </el-form-item>
            <el-form-item label="详细地址" prop="address">
              <el-input v-model="form.address" type="textarea" maxlength="100" show-word-limit placeholder="请输入内容" />
            </el-form-item>
            <el-form-item label="经度" prop="longitude">
              <el-input-number v-model="form.longitude" :precision="6" controls-position="right" :step="0.1" style="width: 100%;">
              </el-input-number>
            </el-form-item>
            <el-form-item label="纬度" prop="latitude">
              <el-input-number v-model="form.latitude" :precision="6" controls-position="right" :step="0.1" style="width: 100%;">
              </el-input-number>
            </el-form-item>
            <el-form-item label="配送范围" prop="deliveryArea">
              <!-- <el-input v-model="form.deliveryArea" placeholder="请输入配送范围" /> -->
              <el-input-number v-model="form.deliveryArea" :precision="2" controls-position="right" :step="0.1" style="width: 100%;">
                <template #suffix>
                  <span>公里</span>
                </template>
              </el-input-number>
            </el-form-item>
            <el-form-item label="区域折扣" prop="regionDiscounts">
              <el-input-number v-model="form.regionDiscounts" :precision="2" controls-position="right" :step="0.1" style="width: 100%;">
                <template #suffix>
                  <span>折</span>
                </template>
              </el-input-number>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in sys_normal_disable"
                  :key="dict.value"
                  :label="parseInt(dict.value)"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="1"></el-col>
        <el-col :span="12">
          <el-row>
            <el-col :span="24">
              <el-form ref="queryRef2" :inline="true" style="float: right;" label-width="68px">
                <el-form-item>
                  <el-input
                    v-model="keywords"
                    style="width: 240px"
                    placeholder="请输入地址"
                    :suffix-icon="Search"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary">搜索</el-button>
                </el-form-item>
              </el-form>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <MapContainer></MapContainer>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Operatingarea">
import { listOperatingarea, getOperatingarea, delOperatingarea, addOperatingarea, updateOperatingarea, changeOperatingareaStatus } from "@/api/business/operatingarea"
import { Search } from '@element-plus/icons-vue'
import MapContainer from "./MapContainer.vue"
// 中国省市区数据，来源 https://github.com/modood/Administrative-divisions-of-China/blob/master/dist/pca-code.json
import regionOptions from "../../../assets/data/pca-code.json"
import { ref } from "vue"

const { proxy } = getCurrentInstance()
const { sys_normal_disable } = proxy.useDict('sys_normal_disable')

const operatingareaList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
// 初始化为true，标记数据未加载完成
const isInitializing = ref(true)
const keywords = ref("")
// 地图
const showMapDialog = ref(true)
// 已选位置数据
const selectedLocation = ref(null)
// 可选：初始经纬度（如果不传则自动定位）
const initialLng = ref(116.404)  // 可选
const initialLat = ref(39.915)   // 可选
const cascaderRef = ref(null)
const selectedLable = ref(null)

const regionProps = {
  expandTrigger: 'hover',
   value: "code",
   label: "name"
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    regionName: null,
    province: null,
    city: null,
    status: null,
  },
  rules: {
    regionName: [{require: true, message: "区域名称不能为空", trigger: "blur"}],
    province: [{ required: true, message: "省份不能为空", trigger: "blur" }],
    city: [{ required: true, message: "运营城市不能为空", trigger: "blur" }],
    regionCode: [{ required: true, message: "区域不能为空", trigger: "blur" }],
    address: [{ required: true, message: "详细地址不能为空", trigger: "blur" }],
    longitude: [{ required: true, message: "经度不能为空", trigger: "blur" }],
    latitude: [{ required: true, message: "纬度不能为空", trigger: "blur" }],
    deliveryArea: [{ required: true, message: "配送范围不能为空", trigger: "blur" }]
  }
})

const { queryParams, form, rules } = toRefs(data)

const handleChange = (value) => {
  console.log(value)
  // 获取选中的节点（返回数组，单选择时取第一个元素）
  const checkedNodes = cascaderRef.value.getCheckedNodes();
  if (checkedNodes.length) {
    // pathLabels 直接返回各级 label 组成的数组（如 ['省', '市', '区']）
    const labels = checkedNodes[0].pathLabels;
    console.log('选中的 Label：', labels); 
    // 也可单独获取某一级的 label，如最后一级：checkedNodes[0].label

    selectedLable.value = labels.join("")
  }
}

// 列表行号
const indexMethod = (index) => {
  return index + 1
}
// 处理位置选择回调
const handleLocationSelect = (location) => {
  console.log('选择的位置:', location)
  selectedLocation.value = location
  
  // 这里可以做其他业务逻辑，比如：
  // - 保存到表单数据
  // - 发送请求到后端
  // - 更新其他组件状态
}

/** 查询运营区域列表 */
function getList() {
  loading.value = true
  // 开始加载，标记为初始化中
  isInitializing.value = true;
  listOperatingarea(queryParams.value).then(response => {
    operatingareaList.value = response.rows
    total.value = response.total
    loading.value = false
    // 等待DOM更新完成后，标记初始化结束（避免渲染时触发事件）
    nextTick(() => {
      isInitializing.value = false;
    });
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    regionName: null,
    province: null,
    city: null,
    region: null,
    address: null,
    longitude: null,
    latitude: null,
    deliveryArea: null,
    regionDiscounts: null,
    deleverNum: null,
    status: 0,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  }
  proxy.resetForm("operatingareaRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 运营区域修改 */
function handleStatusChange(row) {
  // 若处于初始化阶段或加载中，直接返回，不处理事件
  if (isInitializing.value || loading.value) {
    return;
  }
  let text = row.status === 0 ? "启用" : "停用"
  proxy.$modal.confirm('确认要"' + text + '"该运营区域吗?').then(function () {
    return changeOperatingareaStatus(row.id, row.status)
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功")
  }).catch(function () {
    row.status = row.status === 0 ? 1 : 0
  })
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加运营区域"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getOperatingarea(_id).then(response => {
    form.value = response.data

    if (form.value.regionCode) {
      // 省市区解析
      form.value.regionCode = form.value.regionCode.split("-")
    }

    open.value = true
    title.value = "修改运营区域"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["operatingareaRef"].validate(valid => {
    if (valid) {
      // 省市区解析
      form.value.regionCode = form.value.regionCode.join("-")
      form.value.region = selectedLable.value

      if (form.value.id != null) {
        updateOperatingarea(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addOperatingarea(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除运营区域编号为"' + _ids + '"的数据项？').then(function() {
    return delOperatingarea(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('business/operatingarea/export', {
    ...queryParams.value
  }, `operatingarea_${new Date().getTime()}.xlsx`)
}

getList()
</script>